package com.github.permissiondog.cancanpbackend.servlet;

import com.github.permissiondog.cancanpbackend.request.ApplicationCreateRequest;
import com.github.permissiondog.cancanpbackend.response.ApplicationResponse;
import com.github.permissiondog.cancanpbackend.response.ApplicationsResponse;
import com.github.permissiondog.cancanpbackend.response.BaseResponse;
import com.github.permissiondog.cancanpbackend.service.ApplicationService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@WebServlet("/applicant/application")
public class ApplicantApplicationServlet extends BaseServlet {
    /**
     * 创建申请
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        var body = bind(req, resp, ApplicationCreateRequest.class);
        if (body == null)   return;

        try {
            var t = new HashMap<Integer, String>();
            body.answers.forEach(a -> t.put(a.questionId, a.answer));
            var app = ApplicationService.getInstance().createApplication(
                    userLoggedIn(req).getId(), body.templateId, t);
            json(resp, ApplicationResponse.builder().ok(true).application(app).build());
        } catch (Exception e) {
            json(resp, BaseResponse.builder().ok(false).msg("创建失败").error(e.getMessage()).build());
        }
    }


    /**
     * 获取申请列表
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            var apps = ApplicationService.getInstance().getApplications(
                    userLoggedIn(req).getId()
            );
            json(resp, ApplicationsResponse.builder().ok(true).applications(apps).build());
        } catch (Exception e) {
            json(resp, BaseResponse.builder().ok(false).msg("创建失败").error(e.getMessage()).build());
        }
    }
}
